﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using pinche_api.Data;
using pinche_api.Models;

namespace pinche_api.Controllers {
    /// <summary>
    /// 拼车信息
    /// </summary>
    public class CarpoolsController:BaseController {
        private readonly SQLiteContext _context;
        /// <summary>
        /// 拼车信息
        /// </summary>
        /// <param name="context"></param>
        public CarpoolsController(SQLiteContext context) {
            _context=context;
        }
        /// <summary>
        /// 根据条件获取拼车信息列表
        /// </summary>
        /// <param name="start">出发地</param>
        /// <param name="over">目的地</param>
        /// <param name="date">日期</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> lists(string start,string over,string date,int page = 1) {
            var carpools = _context.Carpool.Join(_context.User,pet => pet.uid,per => per.id,(pet,per) => new CarpoolView {
                id=pet.id,
                date=pet.date,
                time=pet.time,
                departure=pet.departure,
                destination=pet.destination,
                gender=pet.gender,
                name=pet.name,
                phone=pet.phone,
                remark=pet.remark,
                surplus=pet.surplus,
                type=pet.type,
                vehicle=pet.vehicle,
                status=pet.status,
                see=pet.see,
                price=pet.price,
                uid=pet.uid,
                avatarUrl=per.avatarUrl,
                dateline=pet.dateline,
            });

            if(!String.IsNullOrEmpty(start)) {
                carpools=from s in carpools
                         where EF.Functions.Like(s.departure,$"%{start}%")
                         select s;
            }
            if(!String.IsNullOrEmpty(over)) {
                carpools=from s in carpools
                         where EF.Functions.Like(s.destination,$"%{over}%")
                         select s;
            }
            if(!String.IsNullOrEmpty(date)) {
                carpools=from s in carpools
                         where EF.Functions.Like(s.date,$"%{date}%")
                         select s;
            }
            carpools=carpools.OrderBy(s => s.date);
            int pageSize = 20;
            var items = await carpools.Skip((page-1)*pageSize).Take(pageSize).ToListAsync();

            return Content(new {
                status = "1",
                msg = "获取成功",
                list = items
            }.ToJson());
        }

        /// <summary>
        /// 根据ID获取拼车信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<Carpool>> GetCarpool(string id) {
            var carpool = await _context.Carpool.FindAsync(id);

            if(carpool==null) {
                return NotFound();
            }

            return carpool;
        }

        /// <summary>
        /// 修改拼车信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="carpool"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> EditCarpool(string id,[FromForm] Carpool carpool) {
            if(id!=carpool.id) {
                return BadRequest();
            }
            _context.Entry(carpool).State=EntityState.Modified;
            try {
                await _context.SaveChangesAsync();
            } catch(DbUpdateConcurrencyException) {
                if(!CarpoolExists(id)) {
                    return NotFound();
                } else {
                    throw;
                }
            }
            return NoContent();
        }
        /// <summary>
        /// 添加拼车信息
        /// </summary>
        /// <param name="carpool"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<Result>> AddCarpool([FromForm] Carpool carpool) {
            Result result = new Result();
            try {
                var user = _context.User.FirstOrDefault(e => e.id==carpool.uid);
                if(user!=null&&!string.IsNullOrWhiteSpace(user.nickName)) {
                    user.phone=carpool.phone;
                    user.gender=carpool.gender;
                    user.name=carpool.name;

                    _context.Entry(user).State=EntityState.Modified;
                    _context.Carpool.Add(carpool);
                    await _context.SaveChangesAsync();

                    result.success=true;
                    result.msg="添加拼车信息成功";
                    result.data=_context.Carpool.FindAsync(carpool.id);

                } else {
                    result.success=false;
                    result.msg="当前用户不存在，请从新登陆！";
                }
            } catch(DbUpdateException ex) {
                result.success=false;
                result.msg=ex.Message;
            }
            //return CreatedAtAction("GetCarpool",new { id = carpool.id },carpool);
            return Ok(result);
        }

        /// <summary>
        /// 删除拼车信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCarpool(string id) {
            var carpool = await _context.Carpool.FindAsync(id);
            if(carpool==null) {
                return NotFound();
            }
            _context.Carpool.Remove(carpool);
            await _context.SaveChangesAsync();
            return NoContent();
        }
        private bool CarpoolExists(string id) {
            return _context.Carpool.Any(e => e.id==id);
        }
    }
}
